<script setup lang="ts">
import { watch, computed, reactive, ref, onMounted } from 'vue'
import { useNaiveForm } from '@/hooks/common/form'
import {
  NDrawer,
  NDrawerContent,
  NForm,
  NFormItem,
  NInput,
  NButton,
  NSpace,
  NRadio,
  NRadioGroup,
  NSelect
} from 'naive-ui'
import type { FormRules } from 'naive-ui'
import { useEditUser, useGetUserRoles, useGetRoles, useEditUserRoles, useAddUser } from '@/api'

defineOptions({
  name: 'UserTableDrawer'
})

interface Props {
  operateType: string
  rowData?: any
}

const props = withDefaults(defineProps<Props>(), {
  operateType: '',
  rowData: {}
})

const show = defineModel<boolean>('show', {
  default: false
})

interface Emits {
  (e: 'submitted'): void
}

const emit = defineEmits<Emits>()

const title = computed(() => {
  return props.operateType === 'add' ? '新增用户' : '编辑用户'
})

const rules: FormRules = {
  username: {
    required: true,
    trigger: ['blur', 'input'],
    message: '用户名不能为空'
  },
  status: {
    required: true,
    type: 'number',
    trigger: ['blur', 'input'],
    message: '用户状态不能为空'
  }
}

const userGenderOptions = [
  {
    label: '男',
    value: '1'
  },
  {
    label: '女',
    value: '0'
  }
]

const userStatusOptions = [
  {
    label: '启用',
    value: 1
  },
  {
    label: '禁用',
    value: 0
  }
]

const roleOptions = ref([])
const handleInitModelRoleOptions = () => {
  useGetRoles().then(({ data }) => {
    roleOptions.value = data.map((item: any) => {
      return {
        label: item.rolename,
        value: item.id
      }
    })
  })
}

const { formRef, validate, restoreValidation } = useNaiveForm()

const model = reactive({
  username: '',
  gender: null,
  nickname: '',
  phone: '',
  email: '',
  status: null,
  roles: []
})

const createDefaultModel = () => {
  return {
    username: '',
    gender: null,
    nickname: '',
    email: '',
    phone: '',
    status: null,
    roles: []
  }
}

const handleInitModel = () => {
  Object.assign(model, createDefaultModel())

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData)
    handleInitModelRoles()
  }
}

const handleInitModelRoles = () => {
  useGetUserRoles({ username: model.username }).then(({ data }) => {
    model.roles = data.map((item: any) => item.id)
  })
}

const closeDrawer = () => {
  show.value = false
}

const handleSubmit = async () => {
  await validate()
  if (props.operateType === 'add') {
    await useAddUser(model)
    await useEditUserRoles(model.username, model.roles)
  } else {
    await useEditUser(model)
    await useEditUserRoles(model.username, model.roles)
  }
  closeDrawer()
  emit('submitted')
}

watch(show, () => {
  if (show.value) {
    handleInitModel()
    restoreValidation()
  }
})

onMounted(() => {
  handleInitModelRoleOptions()
})
</script>

<template>
  <n-drawer v-model:show="show" :width="340" placement="right">
    <n-drawer-content :title="title">
      <n-form ref="formRef" :model="model" :rules="rules">
        <n-form-item label="用户名" path="username">
          <n-input v-model:value="model.username"></n-input>
        </n-form-item>
        <n-form-item label="性别" path="gender">
          <n-radio-group v-model:value="model.gender"
            ><n-radio
              v-for="item in userGenderOptions"
              :key="item.value"
              :value="item.value"
              :label="item.label"
          /></n-radio-group>
        </n-form-item>
        <n-form-item label="昵称" path="nickname">
          <n-input v-model:value="model.nickname"></n-input>
        </n-form-item>
        <n-form-item label="手机号" path="phone">
          <n-input v-model:value="model.phone"></n-input>
        </n-form-item>
        <n-form-item label="邮箱" path="email">
          <n-input v-model:value="model.email"></n-input>
        </n-form-item>
        <n-form-item label="用户状态" path="status">
          <n-radio-group v-model:value="model.status">
            <n-radio
              v-for="item in userStatusOptions"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            />
          </n-radio-group>
        </n-form-item>
        <n-form-item label="分配角色" path="roles">
          <n-select v-model:value="model.roles" multiple :options="roleOptions" />
        </n-form-item>
      </n-form>
      <template #footer>
        <n-space :size="16">
          <n-button @click="closeDrawer()">取消</n-button>
          <n-button @click="handleSubmit()" type="primary">提交</n-button>
        </n-space>
      </template>
    </n-drawer-content>
  </n-drawer>
</template>

<style scoped></style>
